<?php 
/**
 * The stock controller has 3 function 
 * 1. manage KTKT orders 
 * 2. manage product in warehouse locate database
 * 3.product review
 * @author Norman
 *
 */
class StockController extends Zend_Controller_Action
{
	const KCREATE_CODE = 1;
	const LOCATION_ACTION_ADD = 1;
	const LOCATION_ACTION_REMOVE = 2;
	
	protected static $arrShopMaping;
	
	
    public function init(){
    	self::$arrShopMaping = unserialize(ARR_APOS_NEW_SHOP_MAPPING);  	
	}
    /**
     * This is an empty Index page 
     */
    public function indexAction(){
	
    	
	/**
	 * KA KT SECTION START
	 */    	
    	
    /**
     * This is main landing page of stock controller 
     * it show the page for warehouse to manager ka kt note s
     */
	}
	public function whManageNoteAction(){
		//setting up internal layout
		$this->_helper->_layout->setLayout('layout');
		
		$sh = new Model_DbTable_Shoplocation();
		$kStatus = new Model_DbTable_Products_Stock_Transferadjuststatus();
		
		$shopList = unserialize(ARR_SHOP_ACTIVE);
		$arrResult = array();
		
		foreach($shopList as $v){			
			$kList = $kStatus->listByShopHeadByDateForWh($v,Model_DatetimeHelper::getLastWeekMonday(),Model_DatetimeHelper::dateToday());
			foreach ($kList as $v2 ){
				$arrResult[] = $v2;
			}
		}
	$this->view->resultList = $arrResult;
		
	}
	/**
	 * This is the page on the right of company info page 
	 * if any ka kt exist , it wil be show in this page 
	 * it will show KT , KT , parts Order and Online Order 
	 * 
	 */
	public function kaktNoticeAction(){
		
		$kStatus = new Model_DbTable_Products_Stock_Transferadjuststatus();
		$orderMonitor = new Model_DbTable_Onlineordermonitor();
		
		
		$sh = new Model_DbTable_Shoplocation();
		$shopHead = $this->_getParam("shop");
		$orderList = $orderMonitor->getOrderByShop($shopHead);
		$this->view->orderList = $orderList;
		$this->view->shopHead = $shopHead;
		
		$passwordRow = $sh->getNameByHead(trim($shopHead));
		$this->view->shoppassword = Model_EncryptHelper::getSslPassword($passwordRow["password_shop"]);
		$dateBegin = Model_DatetimeHelper::getLastWeekMonday();
		$dateEnd = Model_DatetimeHelper::getThisWeekSunday();
		$kList = $kStatus->listByShopHeadByDateForWh($shopHead, $dateBegin, $dateEnd);

		$this->view->kList = $kList;

		if($_POST){
			if($_POST["driver"]=="cwddd"){
				
				$kStatus->updateDelivery($_POST["id_record"]);				 	
			}		
		}
	}
	
	/**
	 * Auto run function for generate data for stock review
	 * get shop/WH stock on review start date
	 * get GRN/Sale record on revie end date(28 after start date)
	 @author leo
	 */
	public function preStockReviewAction(){
		ini_set('max_execution_time', 0);
		$reviewHistory = new Model_DbTable_Products_Productsreviewhistory(Zend_Registry::get('db_remoteapp'));
		$product = new Model_DbTable_Productsva(Zend_Registry::get('db_remoteapp'));
		$pSales = new Model_DbTable_Products_Sales(Zend_Registry::get('db_remoteapp'));
		$gnDetail = new Model_DbTable_Apos_Stock_Grndataold(Zend_Registry::get('db_allapos'));
		$gnData = new Model_DbTable_Apos_Stock_Grnold(Zend_Registry::get('db_allapos'));
		$stkWh = Model_Aposinitnew::initProBalanceAll();
		
		$dateStart = '2015-01-05';
		$todayDate = Model_DatetimeHelper::dateToday();
		$lastReviewStart = '2014-11-09';
		$lastReviewEnd = '2014-12-07';
		$currentReviewStart = '2014-12-08';
		$currentReviewEnd = '2015-01-04';
		$test = false;
		while($test == false){
			if($todayDate >=$currentReviewStart && $todayDate <= $currentReviewEnd){
		
				$test = true;
			}else{
				$lastReviewStart = date('Y-m-d',strtotime('+28 day', strtotime($lastReviewStart)));
				$lastReviewEnd = date('Y-m-d',strtotime('+28 day', strtotime($lastReviewEnd)));
				$currentReviewStart = date('Y-m-d',strtotime('+28 day', strtotime($currentReviewStart)));
				$currentReviewEnd = date('Y-m-d',strtotime('+28 day', strtotime($currentReviewEnd)));
				$test = false;
			}
		}
		$shopList = unserialize(ARR_APOS_NEW_SHOP_MAPPING);
		$productList = $product->listAllProducts();

		$tmpArrStock = array();
		$arrStock = array();
		
		if($todayDate == $currentReviewStart || $todayDate == $currentReviewEnd){
			
			foreach ($productList as $k => $v){
				$diff = Model_DatetimeHelper::dateDiff($currentReviewStart, $v['review_date']);

				if($v['review_action'] != 1 && $v['review_action'] != 5 || ($v['review_action'] == 1 && $diff >= 54)){
			
						$tmpArrStock[trim($v['code_product'])]['shop_qty'] = 0;
						$tmpArrStock[trim($v['code_product'])]['wh_qty'] = 0;
						$tmpArrStock[trim($v['code_product'])]['sale_total'] = 0;
						$tmpArrStock[trim($v['code_product'])]['gn_qty'] = 0;
						
				}

			}
		}
		
		//get wh/shop stock 
		if($todayDate == $currentReviewStart){
			
			foreach ($tmpArrStock as $k => $v){
				foreach($shopList as $shopK => $shopV){
					$stk = Model_Aposinitnew::initProStock($shopK);
					$stkLine = $stk->getStockBalance($k, $shopV);
					
					if($stkLine){
						$tmpArrStock[$k]['shop_qty'] += (int)$stkLine['BALANCE'];
					}
					
				}
				$stkLineWh = $stkWh->getStockBalance($k,'WH');
				if($stkLineWh){
					$tmpArrStock[$k]['wh_qty'] = (int)$stkLineWh['BALANCE'];
				}
			}
			

			foreach ($tmpArrStock as $barcode => $qty){
				$reviewHistory->addHistory($barcode, $qty['shop_qty'], $qty['wh_qty'], 0, 0,$currentReviewEnd);
			}
			
		}
		
		//get Gn/sale total 
		if($todayDate == $currentReviewEnd){

			$gnList = $gnData->getGrnByDate($lastReviewStart, $lastReviewEnd);
			
			foreach ($gnList as $k2 => $v2){
				$gnProduct[] = $gnDetail->getScode(trim($v2['GRN_NO']));
			}
			
			
			$gnStock = array();
			if($gnProduct){
				foreach ($gnProduct as $k2 => $v2){
						
					foreach ($v2 as $k3 => $v3){
						$gnStock[trim($v3['SCODE'])] = 0;
					}
				}
				foreach ($gnProduct as $k2 => $v2){
			
					foreach ($v2 as $k3 => $v3){
						$gnStock[trim($v3['SCODE'])] += $v3['REC_QTY'];
					}
				}
			}
			
			foreach ($tmpArrStock as $code => $value){
				$arrStock[$code] = $value;
				if(isset($gnStock[$code])){
					$arrStock[$code]['gn_qty'] = $gnStock[$code];
				}
				$saleQty = $pSales->getSalesByCode($code);
				$rrp = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/get-old-apos-product-pricea/barcode/".$code);
			
				if($saleQty){
					$arrStock[$code]['sale_total'] = $saleQty['sales_w1'] + $saleQty['sales_w2'] + $saleQty['sales_w3'] + $saleQty['sales_w4'];
				}
				$arrStock[$code]['rrp'] = $rrp;
			}

			foreach($arrStock as $k2 => $v2){
				if($v2['gn_qty'] != 0 && $v2['sale_total'] != 0){
					$reviewHistory->updateQty($k2, $currentReviewEnd, $v2['gn_qty'], $v2['sale_total'],$v2['rrp']);
				}
			}
		}
	}
	
	/**
	 * This function is for stock review all products
	 * Review product every 3 month except products sale < X% 
	 @author leo
	 */
	
	public function stockReviewAction(){
		ini_set('max_execution_time', 0);
		$reviewHistory = new Model_DbTable_Products_Productsreviewhistory();
		$product = new Model_DbTable_Productsva();
		$pSales = new Model_DbTable_Products_Sales();

		$fl = new Model_Fileshandler();
		
		$dateStart = '2015-01-05';
		$rate = $this->_getParam('rate');

		$todayDate = Model_DatetimeHelper::dateToday();
		$lastReviewStart = '2014-11-09';
		$lastReviewEnd = '2014-12-07';
		$currentReviewStart = '2014-12-08';
		$currentReviewEnd = '2015-01-04';
		$test = false;
		
		while($test == false){
			if($todayDate >=$currentReviewStart && $todayDate <= $currentReviewEnd){
	
				$test = true;
			}else{
				$lastReviewStart = date('Y-m-d',strtotime('+28 day', strtotime($lastReviewStart)));
				$lastReviewEnd = date('Y-m-d',strtotime('+28 day', strtotime($lastReviewEnd)));
				$currentReviewStart = date('Y-m-d',strtotime('+28 day', strtotime($currentReviewStart)));
				$currentReviewEnd = date('Y-m-d',strtotime('+28 day', strtotime($currentReviewEnd)));
				$test = false;
			}
		}

		$shopList = unserialize(ARR_APOS_NEW_SHOP_MAPPING);
		
		if(isset($_POST['final_submit'])){
			if(!empty($_POST['action'])){
				foreach ($_POST['action'] as $k => $v){
		
					//$product->updateReviewInfo($k, $v, $currentReviewStart);
					//$reviewHistory->updateHistory($k, $lastReviewEnd, $v, $currentReviewStart);
		
				}
			}
				
		}
		
		if($rate){
			$this->view->rateInput = true;
			$this->view->rate = $rate;
		}else{
			$this->view->rateInput = false;
		}
		
		$this->view->dateStart = $lastReviewStart;
		$this->view->dateEnd = $lastReviewEnd;
		
		
		$tmparrStock = $reviewHistory->listProductByDate($lastReviewEnd);
		$this->view->arrStock = $tmparrStock;
		if(empty($tmparrStock)){
			$this->view->reviewEnd = true;
		}
		/*
		foreach ($tmparrStock as $k => $v){
			$rrp = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/get-old-apos-product-pricea/barcode/".$v['product_barcode']);
			if($rrp){
				$reviewHistory->updateRrp($v['id_no'] ,$rrp);
			}
		}
		*/
		$arrStock = array();
	
		if(isset($_POST['submit'])){
			$url = "/stock/stock-review/rate/".$_POST['rate'];
			$this->_redirect($url);
		}
		
		
		
		if(isset($_POST['finish'])){
			$countNever = 0;
			$countView = 0;
			$countClear = 0;
			$countDiscount = 0;
			$countDisposal = 0;
			$countTotal = 0;
			
			$reviewList = array();
			$discountList = array();
			$clearanceList = array();
			$disposaList = array();
			$nRList = array();
			$reviewResut = $reviewHistory->listReviewProductByDate($lastReviewEnd);
			if($reviewResut){
				foreach ($reviewResut as $k => $v){
						$pTitle = $product->getProductNameByCode($v['product_barcode']);
					
						if($v['review_action'] == 1){
							$countView ++;
							$reviewList[$v['product_barcode']] = $pTitle;
						}
						if($v['review_action'] == 2){
							$countDiscount ++;
							$discountList[$v['product_barcode']] = $pTitle;
						}
						if($v['review_action'] == 3){
							$countClear ++;
							$clearanceList[$v['product_barcode']] = $pTitle;
						}
						if($v['review_action'] == 4){
							$countDisposal ++;
							$disposaList[$v['product_barcode']] = $pTitle;
						}
						if($v['review_action'] == 5){
							$countNever ++;
							$nRList[$v['product_barcode']] = $pTitle;
						}
						$countTotal ++;
					}
					
	
				$this->renderScript('/stock/stock-review-done.phtml');
				$this->view->dateStart = $lastReviewStart;
				$this->view->dateEnd = $lastReviewEnd;
				
				echo 'Total '.$countTotal.' Items have been make decision<br/><br/>';
				echo 'Total '.$countView.' Items have reviewed<br/><br/>';
				echo 'Total '.$countDiscount.' Items status change to discount<br/><br/>';
				echo 'Total '.$countClear.' Items status change to clearance<br/><br/>';
				echo 'Total '.$countDisposal.' Items status change to disposal<br/><br/>';
				echo 'Total '.$countNever.' Items status change to Never Review<br/><br/>';
				$currentReviewEnd = date('Y-m-d',strtotime('+29 day', strtotime($currentReviewEnd)));
				echo 'Next review date is '.$currentReviewEnd;
					$fileName = 'Stock_Review_Report_'.$lastReviewStart."_".$lastReviewEnd;
					$fl->exportReviewReport($fileName, $lastReviewStart, $lastReviewEnd, $discountList, $clearanceList, $disposaList, $nRList,$reviewList);
					echo "<br/><br/>"."<a href=\"http://".WEB_IP."/export/stockReview/{$fileName}.xls\" >Download File HERE</a><br/>";
				
			}else{
				echo "You did not choose any option";
			}
		}
		
	}
	
	/**
	 * Check KAKT BY SHOP this page is for shop to check there own KAKT
	 */
	public function checkShopKaktAction(){
		
		$shopHead = $this->_getParam("shop");
		$kNote = new Model_DbTable_Products_Stock_Transferadjuststatus();
		
		$dateBegin = Model_DatetimeHelper::getLastWeekMonday();
		$dateEnd = Model_DatetimeHelper::getThisWeekSunday();		
		
		$twoWeekBegin = "2013-01-01";
		$twoWeekEnd = Model_DatetimeHelper::adjustDays("sub", $dateBegin,1);
		
		
		$recentList = $kNote->listByShopHeadByDate($shopHead, $dateBegin, $dateEnd);
		$oldList = $kNote->listByShopHeadByDate($shopHead, $twoWeekBegin, $twoWeekEnd);
		
		$this->view->shopHead = $shopHead;
		$this->view->recentList = $recentList;
		$this->view->oldList = $oldList;		
	}
	
	public function checkShopStockAction(){
		
		$shop = $this->_getParam("shop");
		if($_POST){
			$this->_redirect("/stock/check-shop-stock/shop/{$shop}/barcode/".trim($_POST['barcode']));
		}
		$barcode = trim($this->_getParam("barcode"));
		$this->view->shop = $shop;
		if(!empty($barcode)){
				
			// find similr product
			if(strpos($barcode,"-")!==false){
					
				$partBarcode = substr($barcode,0,strrpos($barcode,"-"));
					
				//echo $partBarcode;
				$strPlist = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/finder-by-short-code/shortcode/".$partBarcode);
				$arrPlist = unserialize(base64_decode($strPlist));

					
				$arrSlist = array();
					
				foreach($arrPlist as $key => $v){
						
					$barCode = trim($v['SCODE']);
					$des = $v['DESCRIPT'];
					$stock = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/get-current-stock/barcode/".$barCode."/shop/".$shop);

					$arrSlist[] = array($barCode,$des,$stock);
				}
				$this->view->arrSlist = $arrSlist;
			
			}else if(strlen($barcode) >12){
			
			// find similr product
	
					
				$partBarcode = substr($barcode,0,10);
					
				//echo $partBarcode;
				$strPlist = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/finder-by-short-code/shortcode/".$partBarcode);
				$arrPlist = unserialize(base64_decode($strPlist));

					
				$arrSlist = array();
					
				foreach($arrPlist as $key => $v){
			
					$barCode = trim($v['SCODE']);
					$des = $v['DESCRIPT'];
					$stock = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/get-current-stock/barcode/".$barCode."/shop/".$shop);
			
					$arrSlist[] = array($barCode,$des,$stock);
				}
				$this->view->arrSlist = $arrSlist;

			}else{
				
				$des = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/get-old-apos-product-description/barcode/".$barcode);
				$stock =  Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/get-current-stock/barcode/".$barcode."/shop/".$shop);
				// find similr product

				$arrSlist[] = array($barcode,$des,$stock);
				
				$this->view->arrSlist = $arrSlist;
				
				
			}
			
		}

	}
	
	
	/**
	 * When add note , this page add note into the db and sending notice to shop
	 */
	public function saveAddNoteAction(){
		
		$knote = new Model_DbTable_Products_Stock_Transferadjuststatus();
		$krecord = new Model_DbTable_Products_Stock_Kaktstatusrecord();
		$sh = new Model_DbTable_Shoplocation();
		$mail = new Model_Emailshandler();	
		$mailBody = "Hi Shop , you should see the change on the company info page 10 secs later";
		
		if($_POST){
			
			$kNumber = trim($_POST["note_number"]);
			$shopHead = trim($_POST["shop_head"]);
			$staffName = $_POST["staff_name"];
			$ktType = $_POST["kt_type"];
			
			$idKakt = $knote->addStatus($kNumber, $staffName, $shopHead,$ktType);
			
			$krecord->addRecord($idKakt,self::KCREATE_CODE, $staffName);
			
			if(substr($kNumber,0,2)=="KT"){
				$str = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/stock/get-kt-detail/ktno/{$kNumber}/shop/{$shopHead}");
			}
			if(substr($kNumber,0,2)=="KA"){
				$str = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/update-adj-suggestion/no/{$kNumber}/shop/{$shopHead}");
			}
			
			//when add kt or ka 
			//get shop freezeed barcode 
			// if need adjust and order 
			// only modify what is in kt/ kt 
			// on friday , show all unhandled-> Adjustment reject / order not fullilled 
			
			
			
			$shopEmail =$sh->getShopMailByHead($shopHead);
			
			$mail->sendNormalEmail($shopEmail,"NEW KA/KT CREATED,Please Check:".$kNumber,$mailBody);
			
			
			
			$this->_helper->redirector("wh-manage-note");
			
			
		}
		
	}
	/**
	 * This functon save the Created KAKT status chagne 
	 */
	public function saveStatusChangeAction(){

		$knote = new Model_DbTable_Products_Stock_Transferadjuststatus();
		$krecord = new Model_DbTable_Products_Stock_Kaktstatusrecord();
		$sh = new Model_DbTable_Shoplocation();
		$mail = new Model_Emailshandler();
		$redAction = "";
		$para = array();
		
		
		if($_POST){

			//Activate WH @todo send email to shop
			if(isset($_POST["btn_activation"])){
				$knote->activeTheTransfer($_POST["id_note_act"],Model_DatetimeHelper::dateToday(), $_POST["staff_name_act"]);
				$krecord->addRecord($_POST["id_note_act"],99,$_POST["staff_name_act"],$_POST["comm_act"]);
				$redAction = "wh-manage-note";
			}
			//Cancel  WH
			if(isset($_POST["btn_can"])){
				$knote->cancelTheTransfer($_POST["id_note_can"]);
				$krecord->addRecord($_POST["id_note_can"],100,$_POST["staff_name_can"]);	
				$redAction = "wh-manage-note";
			}
			//Edit WH @todo send email to shop
			if(isset($_POST["btn_edit"])){
				$knote->updateStatus($_POST["id_note_edit"],$_POST["status_code_edit"]);
				$krecord->addRecord($_POST["id_note_edit"],$_POST["status_code_edit"],$_POST["staff_name_edit"],$_POST["comment_edit"]);
				$redAction = "wh-manage-note";
			}
			//Only Add Comment Warehouse @todo send email to shop
			if(isset($_POST["btn_comment_wh"])){
				$krecord->addRecord($_POST["id_note_comm_wh"],21,$_POST["staff_name_wh"],$_POST["comm_wh"]);
				$redAction = "wh-manage-note";
			}
			/**
			 * Shop Changes to Save
			 */
			//Shop found problem @todo send email to wh jeffery
			if(isset($_POST["btn_edit_sh"])){
				$knote->updateStatus($_POST["id_note_edit_sh"],4);
				$krecord->addRecord($_POST["id_note_edit_sh"],4,$_POST["staff_name_edit_sh"],$_POST["comment_edit_sh"]);
				$redAction = "check-shop-kakt";
				$para["shop"] =$_POST["shophead_sh"];				
			}			
			//shop found no issue @todo send email to wh jeffery
			if(isset($_POST["btn_wait_act"])){
				
				$knote->updateStatus($_POST["id_note_act_sh"],2);
				$krecord->addRecord($_POST["id_note_act_sh"],2,$_POST["staff_name_act_sh"],$_POST["comm_act_sh"]);
				$redAction = "check-shop-kakt";
				$para["shop"] =$_POST["shophead_sh"];				
				
			}			
			
			//Only Add Comment Shop @todo send email to wh jeffery
			if(isset($_POST["btn_comment_sh"])){
				$krecord->addRecord($_POST["id_note_comm_sh"],31,$_POST["staff_name_sh"],$_POST["comm_sh"]);
				$redAction = "check-shop-kakt";
				$para["shop"] =$_POST["shophead_sh"]; 
			}
			
		}	
			
			
		$this->_helper->redirector($redAction,"stock",null,$para);
			

			
		
		
	}
	/**
	 * This function is nolonger in use 
	 */
	public function whImportKaktAction(){

		$knote = new Model_DbTable_Products_Stock_Transferadjuststatus();
		$krecord = new Model_DbTable_Products_Stock_Kaktstatusrecord();
		$sh = new Model_DbTable_Shoplocation();
		$mail = new Model_Emailshandler();
		$mailBody = "Hi Shop , youshould see the change on the company info page 10 secs later";
				
		
		$arrResult = array();
		
		if($_POST){	
			//var_dump($_POST);		
			$list = trim($_POST["list"]);
			$list = trim(substr($list,1)); 
			$arrList = explode("|", $list);
			
			foreach($arrList as $k => $v){

			
				if($k%2 == 1){
					$arrtmp = array();
					
					if(trim($v)!=""){
						
						//echo "Found KA:".trim($v);
						$arrtmp[0] = trim($v);
						
						//echo "For Shop:".$arrList[$k-1]."<br />";
						
						
						
						if(trim($arrList[$k-1])==""){ 
							//echo "ERROR you missing the shop head"."<br />"; 
							$arrtmp[1] = "MISSING SHOPHEAD"; 
							$arrtmp[2] = "NO ACTION";  }					
						else{
							
							//echo "Do the insert, sending mail"."<br />";
							
							$kNumber = trim($v);
							$shopHead = trim($arrList[$k-1]);
							$staffName = trim($_POST["staff_name"]);
								
							$idKakt = $knote->addStatus($kNumber, $staffName, $shopHead);
								
							$krecord->addRecord($idKakt,self::KCREATE_CODE, $staffName,null);
								
							$shopEmail =$sh->getShopMailByHead($shopHead);
								
							//change to shop email
							/**
							 * @todo : change to shop email
							 */
							$mail->sendNormalEmail("eco3@phonecollection.com.au","NEW KA/KT CREATED,Please Check:".$kNumber,$mailBody);
							
							$arrtmp[1] = $arrList[$k-1]; 
							$arrtmp[2] = "INSERTED | EMAILED";
							
						}
					}
					else{
						
						$arrtmp[0] = "NOT FOUND";
						$arrtmp[1] = $arrList[$k-1];
						$arrtmp[2] = "NO ACTION";						
						
						
						//echo "NO KA KT FOUND";
						//echo "For Shop:".$arrList[$k-1]." do nothing <br />";
						
					}
					
				$arrResult[] = $arrtmp;	
										
				}
				
				
				
				
			}
			
		}
		
		$this->view->arrResult = $arrResult;	
	}
	/**
	 * KA KT Interface for driver , this page is no longer in use 
	 */
	public function driverAction(){
		$sh = new Model_DbTable_Shoplocation();
		$this->view->shopList = $sh->listHead();
		
		$name = $this->_getParam("name");
		$kStatus = new Model_DbTable_Products_Stock_Transferadjuststatus();
		
		$newKaKtList = $kStatus->listByStatusCode(1);
		
		$arrShop = array();
		
		foreach($newKaKtList as $key => $v){
			$arrShop[] = array($v["shop_head"],$v["date_delivery"]);
		}
		
		$this->view->stList = $arrShop;
		
		if($_POST){
			$shopName = end($_POST);		
			foreach($newKaKtList as $key => $v){
				if($shopName==$v["shop_head"]){
					$kStatus->updateDelivery($v["id"]);
				}
				
			}		
		
				
		}
		
	}
	
	/**
	 * geting kt details function is to copy the apos KT into the main db so the staff can scan and check 
	 */	
	public function getKtDetailAction(){
		//echo  $res = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/caaudit/mini-circle");
		$ktNo = trim($this->_getParam("ktno"));
		$shop = trim($this->_getParam("shop"));
		
		$ktData = Model_Aposinitnew::initKtData($shop);
		//d($ktData,self::$arrShopMaping[$shop]);
		$kList = $ktData->listKT($ktNo, self::$arrShopMaping[$shop]); 
		
		$ktMirror = new Model_DbTable_Apos_Mirror_Aposktmirror(Zend_Registry::get('db_remoteapp'));
		$proDes = new Model_DbTable_Apos_Stock_Productdes(Zend_Registry::get('db_allapos'));
		$orderWeekly = new Model_DbTable_Order_Weeklyorder(Zend_Registry::get('db_remoteapp'));
		$spHead = new Model_DbTable_Shoplocation(Zend_Registry::get('db_remoteapp'));
		$this->view->shopEmail = $spHead->getShopMailByHead($shop);
		$noOrder = "PD".$shop.Model_DatetimeHelper::getThisWeekMonday('');
		
		
		$proStock = Model_Aposinitnew::initProStock($shop);
		
		$ktMirror->deleteKtmirrorByNo($ktNo,$shop);
		
		$arrDiff = array();
		foreach($kList as $ktLine){
			$desLine = $proDes->getAposDes(trim($ktLine['SCODE']));
			$stockLine = $proStock->getStockBalance(trim($ktLine['SCODE']),self::$arrShopMaping[$shop]);
			$ktMirror->addAposktmirror($ktNo, trim($ktLine['SCODE']),$desLine['DESCRIPT'],(int)$ktLine['QTY'],Model_DatetimeHelper::dateToday(),$stockLine['BALANCE'],$shop);
		
			$orderLine = $orderWeekly->barcodeExistInOrder(trim($ktLine['SCODE']),$noOrder);
			if(!$orderLine){
				$arrDiff[] = array(trim($ktLine['SCODE']),$desLine['DESCRIPT'],'+'.(int)$ktLine['QTY']);
			}
			else{
				if((int)$ktLine['QTY'] > (int)$orderLine['qty_order'] ){
					$arrDiff[] = array(trim($ktLine['SCODE']),$desLine['DESCRIPT'],(int)$ktLine['QTY'] - (int)$orderLine['qty_order']); // act - system
				}
				// if order exist , update act sent
				if( (int)$ktLine['QTY'] != (int)$orderLine['qty_order'] ){
					$orderWeekly->updateSendQty((int)$orderLine['id_order'],(int)$ktLine['QTY']);
				}
			}
			
		}
		$this->view->arrDiff = $arrDiff;
		$this->view->kt = $ktNo;
		$this->view->shop = $shop;
		//d($arrDiff);
	
	}
	/**
	 * For The New KT Counter for warehouse
	 * this is the actual counting part 
	 * before warehouse sending anything out using this page to count the Qty and then export the KT
	 */
	public function countKtWarehouseAction(){
		
		$shop = $this->_getParam("shop");
		//generate order no
		
		$preFix = "PD";
		$datePD = Model_DatetimeHelper::getThisWeekMonday("");
		$noOrder = $preFix.$shop.$datePD;
		
		$noOrderExt = $this->_getParam("orderno");
		
		if(trim($noOrderExt)!="") {
				$noOrder = $noOrderExt;
		}
		
		$this->view->noOrder = $noOrder;
		$weeklyOrder = new Model_DbTable_Order_Weeklyorder();
		
		$shopCode = strtoupper(substr($noOrder,2,4));
		//d($shopCode);
		$lh = new Model_DbTable_Shoplocation();
		$this->view->shopEmail = $lh->getShopMailByHead($shopCode);
		
		
		if($_POST){
			
			//d($_POST);
			
		
				
				$input =  strtoupper(trim($_POST['input_field']));
				$qty = $_POST['input_qty_show'];
				
				$this->view->inputBarcode = $input;
				
				
				
				if(is_numeric($qty)){
					$qty = (int)$qty;
					$this->view->inputQty = $qty;
				}
				
				$orderLine = $weeklyOrder->barcodeExistInOrder($input, $noOrder);
				
				
				if(!$orderLine){ // check if it is combine barcode

					$scode = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/match-apos-bcode/bcode/".trim($input));
						if(trim($scode)!=""){
							$orderLine = $weeklyOrder->barcodeExistInOrder(trim($scode), $noOrder);
							
							
						}
					}
				
				if(!$orderLine){
					// it is extra
					echo '<script language = "javascript" >alert("The Barcode: '.$input.' , We Never Able to find it in this order, It will not be able to add in"); </script>';
					
				}else{
					
					$willSend = $orderLine['act_send'];
					$idOrderLine = $orderLine['id_order'];
					
					$willSend += $qty;
					
					$weeklyOrder->updateSendQty($idOrderLine, $willSend);			
				}
					
		
			
			
			
		}
		
		
		$orderList = $weeklyOrder->getOrderByNo($noOrder);
		
		$arrUnCount = array();
		$arrExtra = array();
		$arrShort = array();
		$arrCorrect = array();
		
		foreach($orderList as $k => $v){
			if($v['stock_wh'] > 0){
			$qtyOrder = $v['qty_order_shop'];
			$actSent = $v['act_send'];
			
			if(($actSent=="" || $actSent == 0) && $qtyOrder > 0){
				
				$arrUnCount[] = array($v['code_product'],$v['des_product'],$qtyOrder,$actSent,$actSent-$qtyOrder);
			}
			if($actSent > $qtyOrder){
				$arrExtra[] = array($v['code_product'],$v['des_product'],$qtyOrder,$actSent,$actSent-$qtyOrder); 
			}
			if($actSent > 0 && $actSent < $qtyOrder ){
				$arrShort[] = array($v['code_product'],$v['des_product'],$qtyOrder,$actSent,$actSent-$qtyOrder);  
			}
			if(($actSent == $qtyOrder) && $qtyOrder > 0){
				
				$arrCorrect[] = array($v['code_product'],$v['des_product'],$qtyOrder,$actSent,$actSent-$qtyOrder); 
			}
			}
		}
		
		$this->view->arrUnCount = $arrUnCount;
		$this->view->arrExtra   = $arrExtra;
		$this->view->arrShort   = $arrShort;
		$this->view->arrCorrect = $arrCorrect;		
		
	
	}
	
	/**
	 * This is the shop page to count the KT
	 * when kt come , using this page to scan and count the KT QTY
	 */
	public function countKtAction(){
		$token = $this->_getParam("token");
		$ktNo = $this->_getParam("ktno");
		$shop = $this->_getParam("shop");
		
		$url = "/stock/count-kt/ktno/{$ktNo}/token/{$token}/shop/{$shop}";
		if(base64_decode($token)!=$ktNo){
			
			$ktNo = "ERROR OCCUR";
		}
		
		$this->view->ktNo = $ktNo;
		
		$ktMirror = new Model_DbTable_Apos_Mirror_Aposktmirror();
		
		$kList = $ktMirror->listKtByNo($ktNo,$shop);
		
		$this->view->orgkList = $kList;
		$this->view->topLine = "Product";
		
		$arrOrg = array();
		$arrUnCount = array();
		$arrExtra = array();
		$arrShort = array();
		$arrCorrect = array();
		
		if(!$_POST){
			foreach($kList as $k=>$v){
				$arrOrg[] = $v['code_product'];
				$arrOrg[] = $v['des_product'];
				$arrOrg[] = $v['qty'];
				$arrOrg[] = $v['qty_received'];
				$arrOrg[] = $v['qty_onhand'];
			}
		}
		
		if($_POST){
			$arrOrg = unserialize(gzuncompress(base64_decode($_POST['org_list'])));
			//finallize, tell warehouse
			if(isset($_POST['btn_report'])){
				//save to KT different -> add comment
				
			}
			//save the differnce
			if(isset($_POST['btn_cancel'])){
				
				$barCodeInput =  strtoupper(trim($_POST['input_barcode']));
				if($barCodeInput!=""){
				$key = array_search($barCodeInput,$arrOrg,true);
				
				$inputQty = $_POST['input_qty'];
				
				if($inputQty == ""){
					//reset
					$arrOrg[$key + 3] = "";
				}
				if($inputQty > 0){
					$arrOrg[$key + 3] -= $inputQty;
					
				}
				if($inputQty < 0){
					//revise qty
					$arrOrg[$key + 3] -= $inputQty;
				}
				
				
				if($arrOrg[$key + 3] == 0){
					
					
					$arrOrg[$key + 3] ="";
				
					if($arrOrg[$key + 2] == 0){
						//remove it 
			
						$ktMirror->deleteUnExpectedItem($ktNo, $barCodeInput,$shop);
						$this->_redirect($url);
						//unset array
						
					}
				}
				
					
				}
				$this->view->inputBarcode = "";
				$this->view->inputQty = "";
				
			}
			
			//cancel last action
			
			 
			//update Qty,write to database
			if(isset($_POST['btn_input_text']) || (!isset($_POST['btn_cancel']) && !isset($_POST['btn_report']))) {
				$barCodeInput =  strtoupper(trim($_POST['input_barcode']));
				$input =  strtoupper(trim($_POST['input_field']));
				$inputQtyShow = trim($_POST['input_qty_show']);
				
				
				$this->view->inputQty = $inputQtyShow;
				
				
				$key = array_search($input,$arrOrg,true);
				
				if($key !== false){
						$arrOrg[$key + 3] += $inputQtyShow;
						//if it is unexpected item remove it if qty reset to zero
						if($arrOrg[$key + 2] == 0 and $arrOrg[$key + 3] == 0 ){
							
							$ktMirror->deleteUnExpectedItem($ktNo,trim($input),$shop);
							$this->_redirect($url);

						}
						else{
							
							$ktMirror->updateReceivedQty($ktNo, $input, $arrOrg[$key+3],$shop);
						}
						
				}
				else{
					//extra barcode
					$scode = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/match-apos-bcode/bcode/".trim($input));
					
					if($scode != ""){
						$input = trim($scode);
						
						$key = array_search($input,$arrOrg,true);
						
						if($key !== false){
							$arrOrg[$key + 3] += $inputQtyShow;
							
							if($arrOrg[$key + 2] == 0 and $arrOrg[$key + 3] == 0 ){
									
								$ktMirror->deleteUnExpectedItem($ktNo,trim($input),$shop);
								$this->_redirect($url);
								
							}
							else{
									
								$ktMirror->updateReceivedQty($ktNo, $input, $arrOrg[$key+3],$shop);
							}
							
							
						}
						else{
							
							$arrOrg[] = trim($input);
							$arrOrg[] = $desProduct = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/get-old-apos-product-description/barcode/".trim($input));
							$arrOrg[] = 0;
							$arrOrg[] = $inputQtyShow;
							$arrOrg[] = 0;
							if(trim($input)!=""){
							$ktMirror->addUnExpectedItem($ktNo, $input, $desProduct, $inputQtyShow,$shop);
							}else{
								
								echo '<script language = "javascript">window.alert("Error May  Occur, If you See This More Than 3 Times, Contact Norman!");</script>';
							}
						}
						
					}
					else{
						
						$arrOrg[] = trim($input);
						$arrOrg[] = $desProduct = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/get-old-apos-product-description/barcode/".trim($input));
						$arrOrg[] = 0;
						$arrOrg[] = $inputQtyShow;
						$arrOrg[] = 0;
						
						if(trim($input)!=""){
						$ktMirror->addUnExpectedItem($ktNo, $input, $desProduct, $inputQtyShow,$shop);
						}
						else{
							echo '<script language = "javascript">window.alert("Error May  Occur, If you See This More Than 3 Times, Contact Norman!");</script>';
						}
						
					}
					


				}
				
				$this->view->inputBarcode = $input;
								
			}
			
			
		}
		
		//working arrOrg -> base 64 ,serial lize
		$this->view->arrOrg = base64_encode(gzcompress(serialize($arrOrg)));
		$arrOrgChunk = array_chunk($arrOrg,5);
		//working on uncount / extra/ less / correct 
		foreach($arrOrgChunk as $k2 => $v2){
			//uncount 
			if(empty($v2[3])){
				$arrUnCount[] = $v2;
			}
			else{
				//correct
				if($v2[2] == $v2[3]){
					$arrCorrect[] = $v2;
				}
				//Extra
				if($v2[2] < $v2[3]){
					$arrExtra[] = $v2;
				}
				//Less
				if($v2[2] > $v2[3] ){
					$arrShort[] = $v2;
				}				
								
			}
		}
		$this->view->arrUnCount = $arrUnCount;
		$this->view->arrCorrect = $arrCorrect;
		$this->view->arrExtra = $arrExtra;
		//send notice email to myself
		if(count($arrExtra) >2 && count($arrExtra) != $_POST['hidden_count'] ){
			
			$mail = new Model_Emailshandler();
			//$mail->sendNormalEmail("eco3@phonecollection.com.au", $shop."more than 3 extra",$ktNo);
		}
		
		
		$this->view->arrShort = $arrShort;		
	}
	

	/**
	 * Add location for barcode 
	 * there are 3 type of location 
	 * 1. pickup locaction 
	 * 2. bulk location 
	 * 3. box number 
	 */	
	public function addLocationAction(){
		
		$staffId = 0;
		$location = new Model_Products_Location();
		$log = new Model_Products_Locationlog();
		if($_POST){
			$arrBarcodes = explode("\n",$_POST['barcodes']);
			
			foreach($arrBarcodes as $key => $v){
				if(trim($v)!=""){
					$location->addLocation(trim(strtoupper($v)), trim(strtoupper($_POST['location_code'])), $_POST['type_location'], 0, Model_DatetimeHelper::dateToday(), Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow(),$staffId);					
					$log->addLocationlog(trim(strtoupper($v)), trim(strtoupper($_POST['location_code'])), Model_DatetimeHelper::dateToday(), Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow(), $staffId,self::LOCATION_ACTION_ADD);
				}				
			}
			
			//d($arrBarcodes);
			echo "<h1>Location Added</h1>";
		}
		
		$source = $this->_getParam("org");
		
		if($source == "elp"){		
			$this->_redirect("/stock/edit-location-product/location/".$_POST['location_code']);
		}	
		
	}
	
	/**
	 * @author Leo
	 * @version 2015-04-24
	 * Add location for Parts/File
	 */
	public function addItemLocationAction(){
		
		$item 	 = new Model_Products_Itemdetail();	 //parts/file info
		$loc  	 = new Model_Products_Location(); 	 //location
		$log  	 = new Model_Products_Locationlog(); //log
		$locType = new Model_Products_LocationType();//locationType
		$dateToday = Model_DatetimeHelper::dateToday();
		
		if(isset($_POST['submit'])){
			$des = $_POST['description'];
			$type = $_POST['type'];
			$subType = $_POST['subtype'];
			$location = $_POST['location'];
		}
	}
	
	/**
	 * check what is in the current loction and edit the product in it
	 */
	public function editLocationProductAction(){
		
		if($_POST){
			
			$this->_redirect("/stock/edit-location-product/location/".trim($_POST['code_location']));
		}
		$this->view->location = $location = trim($this->_getParam("location"));
		
		$loc = new Model_Products_Location();
		$log = new Model_Products_Locationlog();		
		
		$pList = $loc->getProductsByLocation($location);
		$arrRes = array();
		
		foreach($pList as $k => $v){
			$tmpArr = $v;
			$tmpArr['des'] =  Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/get-old-apos-product-description/barcode/".$v['code_product']);
			$tmpArr['sk'] =  Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/get-current-stock/barcode/".$v['code_product']);
			$arrRes[] = $tmpArr;
		}
		
		$this->view->pList = $arrRes;
		//d($arrRes);
		//
	}
	
	public function editProductAllAction(){
		if($_POST){
			if(isset($_POST['code_product'])){
				$this->_redirect("/stock/edit-product-all/barcode/".trim($_POST['code_product']));
			}
			
			if(isset($_POST['category_product'])){
				$this->_redirect("/stock/edit-product-all/category/".$_POST['category_product']);
			}
		}
		
		$loc = new Model_Products_Location();
		$des = new Model_Products_Itemdetail();
		$categoryType = new Model_Products_LocationType();
		$locList = array();
		
		$barcode = trim($this->_getParam("barcode"));
		$category = trim($this->_getParam("category"));
		
		$arrPlistLocations = array();
		$barcodeList = $des->listAll();
		$cateList = $categoryType->listAll();
		if(trim($barcode)!="" ){				
			
				$locList = $loc->getLocationsByProduct($barcode);
				$detail = $des->getItem($barcode);
				
				$this->view->codeProduct = $barcode;
				
				$this->view->desProduct =$detail;
				$this->view->locList = $locList;
				
		// find similr product
		}else if($category != ""){
			
			$this->view->category = $category;
			$pList = array();
			$locList = $loc->getProductByTypeLocation($category);
			foreach ($locList as $k => $v){
				$detail = $des->getItem($v['code_product']);
				$pList[$v['code_product']] = $v;
				$pList[$v['code_product']]['des'] = $detail['item_description']; 
			}
			$this->view->pList = $pList;
			//d($pList);
		}
		
		$this->view->barcodeList = $barcodeList;
		$this->view->category = $cateList;
			
	}
	
	/**
	 * this is not start yet , this is for mobile phone api 
	 */
	public function editLocationProductApiAction(){
			
	}
	/**
	 * giving a barcode and show all the location of this barcode 
	 */
	public function editProductLocationAction(){
		
		if($_POST){
			$this->_redirect("/stock/edit-product-location/barcode/".trim($_POST['code_product']));
		}
		
		$loc = new Model_Products_Location();
		$locList = array();
		
		$barcode = trim($this->_getParam("barcode"));
		
		$arrPlistLocations = array();
		
		if(trim($barcode)!="" ){				
			
				$locList = $loc->getLocationsByProduct($barcode);
		
				$this->view->codeProduct = $barcode;
				$this->view->desProduct = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/get-old-apos-product-description/barcode/".$barcode);
				$this->view->skProduct =  Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/get-current-stock/barcode/".$barcode);
		// find similr product
		if(strpos($barcode,"-")!==false){
			
			$partBarcode = substr($barcode,0,strrpos($barcode,"-"));
			
			//echo $partBarcode;
			$strPlist = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/finder-by-short-code/shortcode/".$partBarcode);
			$arrPlist = unserialize(base64_decode($strPlist));
			
			//d($arrPlist);
			
			$arrSlist = array();
			
			foreach($arrPlist as $key => $v){
					
				$barCode = $v['SCODE'];
				$des = $v['DESCRIPT'];
				$stock = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/get-current-stock/barcode/".$barCode);
				$locations = $loc->getLocationsByProduct($barCode);
				
				$arrSlist[] = array($barCode,$des,$stock,$locations);
			}
			$this->view->arrSlist = $arrSlist;
			//d($arrSlist);
		}
		
		}
		
		$this->view->locList = $locList;	
		//Kint::trace();
	}
	
	/**
	 * API funcion  give product location when the export location request for 
	 * 1. online order 
	 * 2. ebay 
	 * 
	 */
	public function getProductLocationAction(){
		
		$this->_helper->layout->disableLayout();
		
		$barCode = trim($this->_getParam("barcode"));
		$loc = new Model_Products_Location();
		$locList = $loc->getLocationsByProduct($barCode);
		$locStr = '';
		foreach($locList as $k => $v){
			$locStr .=$v['code_location']." ";
		}
		echo trim($locStr);
	}
	
	/**
	 * remove the barcode in this location 
	 */
	public function removeProductLocationAction(){
		
		$idStaff = 0;
		$source = $this->_getParam("org");
		$barCode = trim($this->_getParam("barcode"));
		$location = trim($this->_getParam("location"));
		
		$loc = new Model_Products_Location();
		$locLog = new Model_Products_Locationlog();
		$loc->removeProductFromLocation($barCode, $location);
		$locLog->addLocationlog($barCode, $location,Model_DatetimeHelper::dateToday(), Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow(), $idStaff, self::LOCATION_ACTION_REMOVE);
		
		if($source == "epl"){
			
			$this->_redirect("/stock/edit-product-location/barcode/".$barCode);
		}
		if($source == "elp"){
				
			$this->_redirect("/stock/edit-location-product/location/".$location);
		}		
		
	}
	
	/**
	 * add product in this location 
	 */
	public function addProductLocationAction(){
		
		$idStaff = 0;
		$source = $this->_getParam("org");
		$loc = new Model_Products_Location();
		$locLog = new Model_Products_Locationlog();		
		
		if($_POST){
			$loc->addLocation(trim($_POST['code_product']),trim($_POST['code_location']), $_POST['type_location'],0, Model_DatetimeHelper::dateToday(), Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow(), $idStaff);
			$locLog->addLocationlog(trim($_POST['code_product']),trim($_POST['code_location']),Model_DatetimeHelper::dateToday(), Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow(), $idStaff, self::LOCATION_ACTION_ADD);
			if($source == "epl"){
			
				$this->_redirect("/stock/edit-product-location/barcode/".trim($_POST['code_product']));
			}		
		
		
		}
				
	
	}
	
	/**
	 * list product do not have a location 
	 */
	public function productWithNoLocationAction(){
		
		$date = $this->_getParam("date_begin");
		
		$order = new Model_DbTable_Order_Weeklyorder();
		$loc = new Model_Products_Location();
		$oList = $order->getOrderByDate($date);
		
		//d($oList);
		$arrNoLoc = array();
		foreach($oList as $list){
			$locRow = $loc->getLocationsByProduct(trim($list['code_product']));
			if(!$locRow){
				$arrNoLoc[$list['code_product']] = $list['des_product'];
			}
		}
		//d($arrNoLoc);
		$this->view->arrNoLoc = $arrNoLoc;
	}
	/**
	 * warehouseStock check by click different button.
	 * a. show all items wh stock < 5 export to csv
	 * b. New product read GN show detail which without position
	 * c. WH stock < 5 not in Z position
	 * d. Show product detail not in Z position if 4 weeks no order 
	 * e. Check option b and c total number, email out when reach limit
	 * 
	 * @author Leo
	 * @version 2014-07-06
	 */
	
	public function warehouseStockCheckAction(){
		$this->_helper->layout()->disableLayout();
		Kint::enabled(false);
		$stock = new Model_DbTable_Productsva();
		$mystock = $stock->listAllProducts();
		$stkPro = Model_Aposinitnew::initProBalanceAll();
		$stkDetail = Model_Aposinitnew::initProDes();
		$gnDetail = new Model_DbTable_Apos_Stock_Grndataold(Zend_Registry::get('db_allapos'));
		$gnData = new Model_DbTable_Apos_Stock_Grnold(Zend_Registry::get('db_allapos'));
		$order = new Model_DbTable_Order_Weeklyorder(Zend_Registry::get('db_remoteapp'));
		$loc = new Model_Products_Location(Zend_Registry::get('db_remoteapp'));
		
		$tmpList = $loc->getZpositionProduct('Z', 'BN');
		$zList = array();
		
		$mail = new Model_Emailshandler();
		$mailAdd = 'neardban@gmail.com'; 
		
		foreach($tmpList as $key => $val){
			$tmp = $val['code_product'];
			array_push($zList, $tmp);
		}
		
		d($zList);
		/*
		$file = '20140715-z_position2.csv';
		$loc = new Model_Products_Location(Zend_Registry::get('db_remoteapp'));
		$log = new Model_Products_Locationlog(Zend_Registry::get('db_remoteapp'));
		$arrResult = array();
		if(empty ($file)){
			$this->view->errorFlag2 = true;
				
			$this->view->errorMessage = "Please import the file";
			$this->renderScript('/products/importCsv.phtml');
			return false;
		}
		
		$change = 0;
		$arrResult = array();
			
		$fl = fopen($file,"r");
			
		while(($lineData = fgetcsv($fl,0)) != false){
				
			$arrResult[] = $lineData;
		}
		
		fclose($fl);
		d($arrResult);
		array_shift($arrResult);
		
		foreach($arrResult as $key4 => $val4){
				$loc->addLocation($val4[1], 'Z', 'BN', 0, Model_DatetimeHelper::dateToday(), Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow(),0);					
				$log->addLocationlog($val4[1], 'Z', Model_DatetimeHelper::dateToday(), Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow(), 0,1);
		}
		*/
		$locList = array();
		$gnArray = array();
		if(isset($_POST['z_position'])){
			$this->_helper->layout()->disableLayout();
			$shop = "WH";
			$myQty = array();
			$myQty2 = array();
			$csvInput = array();
				foreach($mystock as $k => $v){
					$tmpArr = array();
					$locList = $loc->getLocationsByProduct($v['code_product']);
					$stk = $stkDetail->matchBcode($v['code_product']);			
					$stkLineWh = $stkPro->getStockBalance($v['code_product'],$shop);
						if((int)$stkLineWh['BALANCE']<=5&& $stk != null){
							$tmpArr = $v;
							$tmpArr['stock_qty'] = (int)$stkLineWh['BALANCE'];
							$tmpArr['location'] = $locList;
							$myQty[] = $tmpArr;
						}if($stk == null){
							$tmpArr2 = $v;
							$tmpArr2['stock_qty'] = (int)$stkLineWh['BALANCE'];
							$tmpArr2['location'] = $locList;
							$myQty2[] = $tmpArr2;
						}
				}
		
		$this->view->stockDetail = $myQty;
		
		$title = array('id_product','barcode','title','stock');
		
		$filename = date('Ymd');
		header("Content-type: text/csv");
		header("Content-Disposition: attachment; filename={$filename}.csv");
		header("Pragma: no-cache");
		header("Expires: 0");
		$outputBuffer = fopen("php://output", 'w');
			
		fputcsv($outputBuffer,$title);
		
		foreach($myQty2 as $k2 => $v2){
				$myarray = array();
				$myarray['id_product'] = $v2['id_product'];
				$myarray['code_product'] = $v2['code_product'];
				$myarray['title_product'] = $v2['title_product'];
				$myarray['stock_qty'] = $v2['stock_qty'];
		

				$csvInput[] = $myarray;
		}
		foreach($csvInput as $k3 => $val3){
			foreach($val3 as $k4 => $val4){
				$lastResult[$k4] = iconv('utf-8', 'gbk', $val4);
			}
			fputcsv($outputBuffer, $lastResult);
		}
		fclose($outputBuffer);
		}
		
		if(isset($_POST['read_gn'])){
			$this->_helper->layout()->disableLayout();
			Kint::enabled(false);
			if($_POST['gn_no']!=null){
				$myGn = $gnDetail->getScode($_POST['gn_no']);

				if($myGn!=false){
					foreach($myGn as $key2 => $val2){
						$tmpArr = array();
							$gnStock = $stkPro->getStockBalance(trim($val2['SCODE']),'WH');
							$myloc = $loc->getLocationsByProduct(trim($val2['SCODE']));
								if($myloc == false && (int)$gnStock['BALANCE']!= false){
									$tmpArr['scode'] = trim($val2['SCODE']);
									$tmpArr['title'] = $stock->getProductNameByCode(trim($val2['SCODE']));
									$tmpArr['qty'] = (int)$gnStock['BALANCE'];
									$tmpArr['location'] = $myloc;
									$gnArray[] = $tmpArr;
								}
								if($myloc!= false && (int)$gnStock['BALANCE']!= false){
									foreach($myloc as $key3 => $val3){
										if($val3['type_location']== 'PL'&& $val3['code_location']==null){
											$tmpArr['scode'] = trim($val2['SCODE']);
											$tmpArr['title'] = $stock->getProductNameByCode(trim($val2['SCODE']));
											$tmpArr['qty'] = (int)$gnStock['BALANCE'];
											$tmpArr['location'] = $myloc;
											$gnArray[] = $tmpArr;
										}
									}
								}
					}
					d($gnArray);
				
				}else{
					$this->view->errorFlag = true;
					$this->view->errorMessage = "Wrong GN number";
					return false;
					}
				
			}else{
				$this->view->errorFlag = true;
				$this->view->errorMessage = "Please input GN number";
				return false;
			}	
			if($gnArray != null){
				$this->renderScript('/products/exportCsv.phtml');
				$title = array('Barcode','Title','Qty');
				
				$filename = 'noPosition';
				header("Content-type: text/csv");
				header("Content-Disposition: attachment; filename={$filename}.csv");
				header("Pragma: no-cache");
				header("Expires: 0");
				$outputBuffer = fopen("php://output", 'w');
					
				fputcsv($outputBuffer,$title);

				foreach($gnArray as $k3 => $val3){
					$lastResult['code_product'] = $val3['scode'];
					$lastResult['title_product'] = $val3['title'];
					$lastResult['stock_qty'] = $val3['qty'];
					
					fputcsv($outputBuffer, $lastResult);
				}
				fclose($outputBuffer);
				
				
				
				/*
				$str = '';
					foreach($gnArray as $k7 => $v7){
							$str .= 'Barcode:'.$v7['scode'].'<br/>'.'Title:'.$v7['title'].'<br/>'.'Qty:'.$v7['qty'].'<br/>'.'<br/>';
					}
					$mail->sendNormalEmail($mailAdd, 'These Items have no location. Please check', 'These items have no location, please check 
							whether it need or not.'.'<br/>'.'The list as below'.'<br/>'.'<br/>'.$str);*/
			}
		}
		if(isset($_POST['read_stock'])){
			$checkLocationResult = array();
			foreach($mystock as $k4 => $v4){
				if(!in_array(trim($v4['code_product']), $zList)){
				$checkStock = $stkPro->getStockBalance(trim($v4['code_product']),'WH');
					if($checkStock <= 5){
						$myloc = $loc->getLocationsByProduct(trim($v4['code_product']));
						$tmpArr = array();
						$tmpArr = $v4;
						$tmpArr['qty'] = $checkStock;
						$tmpArr['location'] = $myloc;
						$checkLocationResult[] = $tmpArr;
					}
				}
			}
			d($checkLocationResult);
			
			if($checkLocationResult != null){
				$str = '';
				foreach($checkLocationResult as $k8 => $v8){
					$str .= 'Barcode:'.$v8['code_product'].'<br/>'.'Title:'.$v8['title_product'].'<br/>'.'Qty:'.$v8['qty'].'<br/>'.'Location:'.$v8['location'][0]['code_location'].'<br/>'.'<br/>';
				}
				$mail->sendActionEmail($mailAdd, 'These Items qty < 5. Please check', 'These items qty < 5, please check 
						whether need to change the location if it is not popular.'.'<br/>'.'The list as below'.'<br/>'.'<br/>'.$str);
			}
			
			
		}
		if(isset($_POST['not_zlist'])){
			$this->_helper->layout()->disableLayout();
			Kint::enabled(false);
			date_default_timezone_set('Australia/Melbourne');
			$date4weeks = date('Y/m/d', time()-30*24*60*60);
			$productCode = $stock->listAllProducts();
			$nogoodList = array();
			$total = 0;
			$str = "";
			
			foreach($productCode as $k2 => $v2){
				$tmpArr = array();
				if(!in_array($v2['code_product'], $zList)){
				$orderDetail = $order->getOrderDetailByDateCode($v2['code_product'], $date4weeks);
					if($orderDetail == false){
						$tmpArr = $v2;
						$nogoodList[] = $tmpArr;
					}else{
						foreach($orderDetail as $k3 => $v3){
							$total += $v3['qty_order'];

						}
					
						if($total == 0){
							$tmpArr = $v2;
							$nogoodList[] = $tmpArr;
						}
					}
				}
			}

			if($nogoodList != null){
				$this->renderScript('/products/exportCsv.phtml');
				$title = array('Id','Barcode','Title');
			
				$filename = 'NotSellWellList';
				header("Content-type: text/csv");
				header("Content-Disposition: attachment; filename={$filename}.csv");
				header("Pragma: no-cache");
				header("Expires: 0");
				$outputBuffer = fopen("php://output", 'w');
				
				fputcsv($outputBuffer,$title);
			
				foreach($nogoodList as $k3 => $val3){
					$lastResult['id_product'] = $val3['id_product'];
					$lastResult['code_product'] = $val3['code_product'];
					$lastResult['title_product'] = $val3['title_product'];
					
					fputcsv($outputBuffer, $lastResult);
				}
				fclose($outputBuffer);
			}

		}
		if(isset($_POST['check_total'])){
			
				$total = 0;
				$dateEnd = $_POST['date_before'];
				$dateBegin = date('Y-m-d',strtotime('-7 day', strtotime($dateEnd)));
				$myGn = array();
				$myGnNo = $gnData->getGrnByDate($dateBegin,$dateEnd);

				foreach($myGnNo as $k5 => $v5){
					$tmpArr = $gnDetail->getScode(trim($v5['GRN_NO']));
					foreach($tmpArr as $k6 => $v6){
						$tmpArr2 = $v6;
						$myGn[] = $tmpArr2;
					}
				}

				if($myGn!=false){
					foreach($myGn as $key2 => $val2){
						$tmpArr = array();
						$gnStock = $stkPro->getStockBalance(trim($val2['SCODE']),'WH');
						$myloc = $loc->getLocationsByProduct(trim($val2['SCODE']));
						if($myloc == false && (int)$gnStock['BALANCE']!= false){
							$tmpArr['scode'] = trim($val2['SCODE']);
							$tmpArr['title'] = $stock->getProductNameByCode(trim($val2['SCODE']));
							$tmpArr['qty'] = (int)$gnStock['BALANCE'];
							$tmpArr['location'] = $myloc;
							$gnArray[] = $tmpArr;
						}
						if($myloc!= false && (int)$gnStock['BALANCE']!= false){
							foreach($myloc as $key3 => $val3){
								if($val3['type_location']== 'PL'&& $val3['code_location']==null){
									$tmpArr['scode'] = trim($val2['SCODE']);
									$tmpArr['title'] = $stock->getProductNameByCode(trim($val2['SCODE']));
									$tmpArr['qty'] = (int)$gnStock['BALANCE'];
									$tmpArr['location'] = $myloc;
									$gnArray[] = $tmpArr;
								}
							}
						}
					}
					$checkLocationResult = array();
					foreach($mystock as $k4 => $v4){
						if(!in_array(trim($v4['code_product']), $zList)){
							$checkStock = $stkPro->getStockBalance(trim($v4['code_product']),'WH');
							if($checkStock <= 5){
								$myloc = $loc->getLocationsByProduct(trim($v4['code_product']));
								$tmpArr = array();
								$tmpArr = $v4;
								$tmpArr['qty'] = $checkStock;
								$tmpArr['location'] = $myloc;
								$checkLocationResult[] = $tmpArr;
							}
						}
					}

					$total = count($gnArray) + count($checkLocationResult);
					if(count($gnArray)>= 50||count($checkLocationResult)>= 60||$total > 100 ){
						foreach($gnArray as $key4 => $val4){
							$str .= 'Barcode:'.$val4['scode'].'<br/>'.'Title:'.$val4['title'].'<br/>'.'Qty:'.$val4['qty'].'<br/>'.'<br/>';
						}
						foreach($checkLocationResult as $key5 => $val5){
							$str .= 'Barcode:'.$val5['code_product'].'<br/>'.'Title:'.$val5['title_product'].'<br/>'.'Qty:'.$val5['qty'].'<br/>'.'Location:'.$val5['location'][0]['code_location'].'<br/>'.'<br/>';
						}
							//$mail->sendNormalEmail($mailAdd, 'These Items no position or qty < 5. Please check', 'These items have no position or qty < 5 may consider whether need to change the location.'.'<br/>'.'The list as below'.'<br/>'.'<br/>'.$str);
					}else{
						echo 'No such items';
					}

				}

		}
		
	}
	/**
	 * This function is for check product barcode create > 2 month but no stock
	 * rare used
	 @author leo
	 */
	public function nostockBarcodeCheckAction(){
		$product = new Model_DbTable_Productsva(Zend_Registry::get('db_remoteapp'));
		$stock = new Model_DbTable_Productstock(Zend_Registry::get('db_remoteapp'));
		$productAposStock = Model_Aposinitnew::initProBalanceAll();
		date_default_timezone_set("Australia/Melbourne");
		$TodayDate = date('Y-m-d', time());
		$twoMonthago = Model_DatetimeHelper::adjustDays("sub",$TodayDate,60);
		$noStockList = array();
		$barcode = $product->listAllProductbyDate($twoMonthago);
		foreach($barcode as $k => $v){
			$whStock = $stock->getWarehouseStock($v['id_product']);
			$tmpArr = array();
			if($whStock == 0){
					$tmpArr['id_product'] = $v['id_product'];
					$tmpArr['code_product'] = $v['code_product'];
					$tmpArr['title_product'] = $v['title_product'];
					$tmpArr['date_introduce'] = $v['date_introduce'];
					$noStockList[] = $tmpArr;
			}
		}

		$codearray = array();
		$finalnoStockList = array();
		$wh = $productAposStock->listStockWhHave();
		foreach($wh as $k2 => $v2){
			array_push($codearray,trim($v2['SCODE']));
		}
		foreach($noStockList as $k3 => $v3){
			if(!in_array($v3['code_product'], $codearray)){
				$tmpArr2[0] = $v3['id_product'];
				$tmpArr2[1] = $v3['code_product'];
				$tmpArr2[2] = $v3['title_product'];
				$tmpArr2[3] = $v3['date_introduce'];
				$finalnoStockList[] = $tmpArr2;
			}
		}
		$mailAdd = 'phonecollection.au@gmail.com';
		$mail = new Model_Emailshandler();
		$fl = new Model_Fileshandler();
		
		
		echo "<br />";
		$exportFileName = "barcodeNoStock".$TodayDate;
		echo "<a href=\"http://".SERVER_IP_COMM."/export/stock/{$exportFileName}.xls\" >{$exportFileName}.xls</a>";
		$url = "http://".SERVER_IP_COMM."/export/stock/{$exportFileName}.xls";
		$fl->exportnoStock($finalnoStockList, $exportFileName);
		$mail->sendActionEmail('neardban@gmail.com', 'The List Items have barcode but no stock', 
		'The list items have created 2 month ago, but there are no stock since then.'.'<br/>'
		.'The link of list as below'.'<br/>'.$url);
		
		
	}
	/**
	 * @auther Norman
	 * Count the order 
	 */
	public function countOrderAction(){
		
		$orderNo = $this->_getParam("no_order");
		
	}
	/**
	 * this is for conned the webiste and control the online order 
	 */
	public function onlineOrderControlAction(){
		$shop = $this->_getParam("shop");
		$oMonitor = new Model_DbTable_Onlineordermonitor();
		$this->view->shop = $shop;
		
		
		
		if($_POST){
			
			$idOrder = $_POST['id_order'];
			$status = 0;
			
			if(isset($_POST['btn_ready'])){
				$status = 14;
			}
			if(isset($_POST['btn_cancel'])){
				$status = 17;
			}
			if(isset($_POST['btn_pickup'])){
				$status = 15;
			}
			
			if($status >0){
				
				$url = "http://".SERVER_IP_COMM."/online/update-online-order-status/id_order/".$idOrder."/status/".$status;
				Model_System_Downloadhelper::downloadUrl($url);
				$oMonitor->updatStatus($idOrder, $status);
				
			}
			
		}
		
		$oList = $oMonitor->getOrderByShop($shop);
		
		$this->view->orderList = $oList;
	}
	
	/**
	 * As requested by Ken , to verify the fullfill rate of warehouse
	 * At the moment , jeffrey will not modify order before export 
	 * if click full fill rate detail page , will show individual shop detail 
	 * if in summary page will only show numbers and %
	 * 
	 */
	
	public function fullfillRateDetailAction(){
		
	$ktNo = $this->_getParam('kt');
		$orderNo = $this->_getParam('od');
		$shop = $this->_getParam('shop');
		
		
		$order = new Model_DbTable_Order_Weeklyorder();
		$ktMirror = new Model_DbTable_Apos_Mirror_Aposktmirror();
		
		
		
		$arrRes = array();
		
		
		$odList = $order->getOrderByNo($orderNo);
		
		foreach($odList as $odLine){
			
			$barcode = trim($odLine['code_product']);
			$qtyOrder = $odLine['qty_order_shop'];
			if(!in_array($barcode, $arrRes,true)){
				if($qtyOrder >0){
					
					$arrRes[] = $barcode;
					$arrRes[] = $qtyOrder;
					$arrRes[] = 0;
					$arrRes[] = $odLine['status_hot'];
					
				}
				
			}
			
		}
		
		$ktList = $ktMirror->listKtByNo($ktNo, $shop);
		
		$find = 0;
		
		foreach($ktList as $ktLine){
			
			$barcode = trim($ktLine['code_product']);
			$qtySend = $ktLine['qty'];
			
			$key = array_search($barcode,$arrRes,true);
			if($key !== false){
				$find ++;
				//d($qtySend);
				$arrRes[$key +2] = $qtySend;
			}
			else{
				$arrRes[] = $barcode;
				$arrRes[] = 0;
				$arrRes[] = $qtySend;
				$arrRes[] = 'NEW';
			}
			
			
			
		}
		
		echo $find;
		
		$arrThree = array_chunk($arrRes, 4);
		
		$full = 0;
		$part = 0;
		$nonfull = 0;
		$new = 0;
		
		//d($arrThree);
		
		foreach($arrThree as $k => $v){
			
			if($v[1] == 0 ){
				
				$new ++;
			}
			else{
				if($v[1] <= $v[2]){
					
					$full ++;
				}
				
				if( $v[1] > $v[2] && $v[2] > 0){
					
					$part ++;
				}
				if( $v[1] > $v[2] && $v[2] == 0){
					
					//d($v);
						
					$nonfull ++ ;
				}
				
				
			}
			
			
		}
		
		$pro = new Model_DbTable_Productsva();
		
		$arrFinal = array();
		
		
		foreach($arrThree as $k => $v){
			$arrFinalTmp = array();
			$arrFinalTmp = $v;
			
			$title = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/get-old-apos-product-description/barcode/".$v[0]);
			
			$intro = $pro->getProductByBarcode($v[0]);
			$arrFinalTmp[] = $title;
			$arrFinalTmp[] = $intro['date_introduce'];
			
			$arrFinal[] = $arrFinalTmp;
		}
		
		$this->view->arrFinal = $arrFinal;
		
		 $totalOrder = $full + $part + $nonfull;
	
		 $fullRate = round($full / $totalOrder,4)*100;
	
		 $partRate = round($part / $totalOrder,4)*100;

		 $nonfullRate = round($nonfull / $totalOrder,4)*100;

		
	}
	/**
	 * this is the summary page of full fill rate 
	 * it list all the shop's full fill rate 
	 */
	public function fullfillRateSummaryAction(){
		
		$db = $this->_getParam('date_begin');
		
		$dateBegin = '';
		$dateEnd = '';
		
		if($db == ''){
			$dateBegin = Model_DatetimeHelper::getLastWeekMonday();
			$dateEnd = Model_DatetimeHelper::getLastWeekSunday();
		}
		else{
			$dateBegin = $db;
			$dateEnd = Model_DatetimeHelper::adjustDays("add", $dateBegin,6);
		}
		

		$ktMirror = new Model_DbTable_Apos_Mirror_Aposktmirror();
		
		
		
		
		$arrShop = unserialize(ARR_SHOP_ACTIVE);
		
		foreach($arrShop as $shop){
			
			$dateBeginShort = str_replace('-','',$dateBegin);
			$odNo = 'PD'.$shop.$dateBeginShort;
			
			
			$ktNo = $ktMirror->ktForOrder($dateBegin, $dateEnd, $shop);
			$url = "http://".SERVER_IP_COMM."/stock/fullfill-rate/kt/".$ktNo."/od/".$odNo."/shop/".$shop;
			
			$strRes = Model_System_Downloadhelper::downloadUrl($url);
			
			//d($strRes,$url);
			
			$arrRes[$shop] = array($ktNo,$odNo,unserialize($strRes));
			// find kt no 
			//$ktmirror			
		}
		
			$this->view->arrRes = $arrRes;
			//d($arrRes);		
	}
	
	/**
	 * API function 
	 * this is for the summary page of the full fill rate 
	 */
	public function fullfillRateAction(){
		
		$this->_helper->layout->disableLayout();
		
		$ktNo = $this->_getParam('kt');
		$orderNo = $this->_getParam('od');
		$shop = $this->_getParam('shop');
		
		
		$order = new Model_DbTable_Order_Weeklyorder();
		$ktMirror = new Model_DbTable_Apos_Mirror_Aposktmirror();
		
		
		
		$arrRes = array();
		
		
		$odList = $order->getOrderByNo($orderNo);
		
		foreach($odList as $odLine){
			
			$barcode = trim($odLine['code_product']);
			$qtyOrder = $odLine['qty_order_shop'];
			if(!in_array($barcode, $arrRes,true)){
				if($qtyOrder >0){
					
					$arrRes[] = $barcode;
					$arrRes[] = $qtyOrder;
					$arrRes[] = 0;
					
				}
				
			}
			
		}
		
		$ktList = $ktMirror->listKtByNo($ktNo, $shop);
		
		$find = 0;
		
		foreach($ktList as $ktLine){
			
			$barcode = trim($ktLine['code_product']);
			$qtySend = $ktLine['qty'];
			
			$key = array_search($barcode,$arrRes,true);
			if($key !== false){
				$find ++;
				//d($qtySend);
				$arrRes[$key +2] = $qtySend;
			}
			else{
				$arrRes[] = $barcode;
				$arrRes[] = 0;
				$arrRes[] = $qtySend;
			}
			
			
			
		}
		
		
		$arrThree = array_chunk($arrRes, 3);
		
		$full = 0;
		$part = 0;
		$nonfull = 0;
		$new = 0;
		
		foreach($arrThree as $k => $v){
			
			if($v[1] == 0 ){
				
				$new ++;
			}
			else{
				if($v[1] <= $v[2]){
					
					$full ++;
				}
				
				if( $v[1] > $v[2] && $v[2] > 0){
					
					$part ++;
				}
				if( $v[1] > $v[2] && $v[2] == 0){
					
					//d($v);
						
					$nonfull ++ ;
				}
				
				
			}
			
			
		}
		
		$totalOrder = $full + $part + $nonfull;
		$fullRate = round($full / $totalOrder,4)*100;
		$partRate = round($part / $totalOrder,4)*100;
		$nonfullRate = round($nonfull / $totalOrder,4)*100;
		
		
		echo serialize(array(
				$totalOrder,
				$full,
				$fullRate,
				$part,
				$partRate,
				$nonfull,
				$nonfullRate,
				$new				
				));
		
	}
}
?>